// Arduino sketch for a simple potmeter based joystick
//
// $Id: joystick.pde 28 2009-10-28 15:49:05Z bram.daams@donders.ru.nl $

// Connections: analog pins for X and Y axis
const byte XAXIS = 0;
const byte YAXIS = 1;

// serial commands
const int cmd_GETX           = 'x';
const int cmd_GETY           = 'y';
const int cmd_GETXY          = 'z';
const int cmd_GETXYt         = 'a';
const int cmd_TOGGLETESTMODE = 't';


unsigned long t;
int     command;
boolean testmode = false;
long    x = 0;
long    y = 0;

void setup()
{
  Serial.begin(115200);	// opens serial port, sets data rate
  Serial.println("Joystick $Revision: 28 $, Ready!");
}

void loop()
{
  if (Serial.available() > 0) {
    // read the incoming byte:
    command = Serial.read();

    switch(command) {
    case cmd_GETX:
      Serial.println(analogRead(XAXIS));
      break;

    case cmd_GETY:
      Serial.println(analogRead(YAXIS));
      break;

    case cmd_GETXY:
      // sample x and y at 'the same time'
      x = analogRead(XAXIS);
      y = analogRead(YAXIS);
      Serial.print(x);
      Serial.print(",");
      Serial.println(y);
      break;

    case cmd_GETXYt:
      // sample x and y and the timestamp at 'the same time'
      x = analogRead(XAXIS);
      t = millis();
      y = analogRead(YAXIS);

      Serial.print(x);
      Serial.print(",");
      Serial.print(y);
      Serial.print(",");
      Serial.println(t);
      break;

    case cmd_TOGGLETESTMODE:
      testmode = !testmode;
      break;

    }
  }

  if (testmode) {
    x = analogRead(XAXIS);
    y = analogRead(YAXIS);

    // show values
    Serial.print("X ");
    Serial.print (x);

    Serial.print(" Y ");
    Serial.println(y);

    // wait 25 miliseconds
    delay(25);
  }
}
